package main

import (
	"flag"
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"os"
	"runtime/pprof"
	"sync"
)

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

type Ips struct {
	ID         string
	IP         string
	CreateTime int64
	UpdateTime int64
	DeleteTime int64
}
func main() {
	// 连接RabbitMQ服务器
	flag.Parse()
	if *cpuprofile !="" {
		f,err:=os.Create(*cpuprofile)
		if err!=nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer  pprof.StopCPUProfile()
	}
	conn, err := amqp.Dial("amqp://guest:guest@127.0.0.1:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()
	// 创建一个channel
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()
	//
	q, err := ch.QueueDeclare(
		"ips", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")
	var wg sync.WaitGroup
	//for i := 0; i <= 255; i++ {
	//	go func(i int) {
	//		for j := 0; j <= 255; j++ {
	//			//go func(j int) {
	//				for k := 0; k < 255; k++ {
	//					//go func(k int) {
	//						for l := 0; l < 255; l++ {
	//							wg.Add(1)
	//							var ips Ips
	//							ips.IP = fmt.Sprintf("%v.%v.%v.%v", i, j, k, l)
	//							//ips.CreateTime = time.Now().Unix()
	//							//id, _ := uuid.NewUUID()
	//							//ips.ID = id.String()
	//
	//							err = ch.Publish(
	//								"",     // exchange
	//								q.Name, // routing key
	//								false,  // mandatory
	//								false,  // immediate
	//								amqp.Publishing{
	//									ContentType: "text/plain",
	//									Body:        []byte(ips.IP),
	//								})
	//							failOnError(err, "Failed to publish a message")
	//							log.Printf(" [x] Sent %s", ips.IP)
	//						}
	//					//}(k)
	//
	//				}
	//			//}(j)
	//
	//		}
	//	}(i)
	//}
	for i:=0;i<1000;i++ {
		go func(i int) {
			for j := 0; j <= 1000; j++ {
				wg.Add(1)
				err = ch.Publish(
					"",     // exchange
					q.Name, // routing key
					false,  // mandatory
					false,  // immediate
					amqp.Publishing{
						ContentType: "text/plain",
						Body:        []byte(fmt.Sprintf("%v,%v\n",i,j)),
					})
				failOnError(err, "Failed to publish a message")
				log.Printf(" [x] Sent %s", fmt.Sprintf("%v,%v\n",i,j))
			}
		}(i)
	}

	wg.Wait()

	//// 消费队列
	//msgs, err := ch.Consume(
	//	q.Name, // queue
	//	"",     // consumer
	//	true,   // auto-ack
	//	false,  // exclusive
	//	false,  // no-local
	//	false,  // no-wait
	//	nil,    // args
	//)
	//failOnError(err, "Failed to register a consumer")
	//// 申明一个goroutine,一遍程序始终监听
	//forever := make(chan bool)
	//
	//go func() {
	//	for d := range msgs {
	//		log.Printf("Received a message: %s", d.Body)
	//	}
	//}()
	//
	//log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	//<-forever
}

// 帮助函数检测每一个amqp调用
func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}
